package com.chinastock.convertor;

import com.chinastock.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.NamePatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;
import org.apache.logging.log4j.util.PerformanceSensitive;

/**
 * @author wangzhendong
 */

@Plugin(name = "serverIpConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({Constant.SERVER_IP})
@PerformanceSensitive("allocation")
public class ServerIpConverter extends NamePatternConverter {
    private static final ServerIpConverter INSTANCE = new ServerIpConverter(null);
    /**
     * Constructor. 构造函数
     *
     * @param options options, may be null, first element will be interpreted as an abbreviation pattern.
     */

    private ServerIpConverter(final String[] options) {
        super("serverIp", "serverIp", options);
    }

    /**
     * 3、内部必须有一个newInstance
     *
     * @param options 构建converter的可选参数
     * @return 可选参数
     */
    public static ServerIpConverter newInstance(final String[] options) {
        if (options == null || options.length == 0) {
            return INSTANCE;
        }
        return new ServerIpConverter(options);
    }

    @Override
    public void format(LogEvent logEvent, StringBuilder toAppendTo) {
        try {
            String serverIp = System.getProperty(Constant.SERVER_IP);
            if (StringUtils.isBlank(serverIp)) {
                serverIp = Constant.DEFAUT_IP;
            }
            toAppendTo.append(serverIp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
